#include "http_client.hpp"

#include "http_processor.hpp"

IMPL_LOGGER(HttpProcessor, logger);

void HttpProcessor::accept_connect(Connection & conn) 
{
	LOG4CPLUS_WARN(logger, "connected. ip: " << conn.net_addr().dot_addr()
			<< ", cid: " << conn.conn_id()._cid);
}

void HttpProcessor::remove_connect(Connection & conn) 
{
	LOG4CPLUS_WARN(logger, "disconnected. ip: " << conn.net_addr().dot_addr()
			<< ", cid: " << conn.conn_id()._cid);
}

void HttpProcessor::process_message(Connection & conn, void * data)
{
	SSTencentPlatRes & res = *(SSTencentPlatRes*)data;

	RequestMap_Iter iter = _request_map.find(conn.conn_id()._cid);
	if (_request_map.end() == iter)
	{
		// @TODO LOG ERROR
		LOG4CPLUS_ERROR(logger, "not found request, maybe timeout. connid: " << conn.conn_id()._cid
								<< ", res: " << res.to_string());
		_remove_vec.push_back(&conn);
		return;
	}

	HttpThreadPool & pool = *HttpClient::instance()._thread_pool;
	
	Response response(iter->second);

	response._res._key_val_map = res._key_val_map;
	
	pool.put_response(response);
	
	_remove_vec.push_back(&conn);
	_request_map.erase(iter);
}

int HttpProcessor::poll()
{
	HttpThreadPool & pool = *HttpClient::instance()._thread_pool;
	
	RequestMap_Iter iter = _request_map.begin();
	for (; iter != _request_map.end(); )
	{
		Request & request = iter->second;

		if (request.timeout())
		{
			Response response(request);
			response._res._err_code = cmd::E_TIMEOUT;
			pool.put_response(response);

			_request_map.erase(iter ++);
		}
		else
		{
			++ iter;
		}
	}

	return 0;
}

